package keeto.com.vn.bms.service;

import keeto.com.vn.bms.utils.BMSSharedPreferences;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BMSReceiver extends BroadcastReceiver {
	public static final String BMSRECEIVER_INTENT ="keeto.com.vn.bms.service.BMSIntent";
	public static final String BMSRECEIVER_GETNOTIFY ="keeto.com.vn.bms.service.Notify";
	private BMSSharedPreferences preferences;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();
		if (action != null) {
			if (BMSRECEIVER_INTENT.equals(action)){

				BMSService.lunchServicegetTimeConnection(context);

			}else if(Intent.ACTION_BOOT_COMPLETED.equals(action)){

				boolean	alarmUp = (PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE) != null);
				Log.e("Da","aa " + alarmUp);
				BMSService.lunchServicegetTimeConnection(context);

			}else if (BMSRECEIVER_GETNOTIFY.equals(action)){
				Log.e("Service "," Run Receiver");

				preferences = new BMSSharedPreferences(context);
				int time =	(Integer) (intent.getExtras().get("TimeConnection") != null ? intent.getExtras().get("TimeConnection"):0);
				Intent it = new Intent(context, BMSReceiver.class);
				it.setAction(BMSRECEIVER_GETNOTIFY);
				if (preferences.getStartNotify(context) != time){
					PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, it,0);
					AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
					alarmManager.cancel(pendingIntent);
					alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),time, pendingIntent);
					Log.e("Service "," Register Receiver");
					preferences.setStartNotify(time);
				}
				if (preferences.getStartNotify(context) != 0){
					BMSService.lunchServicegetNotify(context);
				}
			}
		}
	}

}
